package logic

import (
	"context"
	"fmt"

	"gb28181/gb28181"
	"gb28181/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PlaybackLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPlaybackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PlaybackLogic {
	return &PlaybackLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PlaybackLogic) Playback(in *gb28181.PlaybackRequest) (*gb28181.PlaybackResponse, error) {
	// 检查设备是否存在
	device, exists := l.svcCtx.ClientMgr.GetDevice(in.DeviceId)
	if !exists {
		return &gb28181.PlaybackResponse{
			Success: false,
			Message: "设备不存在",
		}, nil
	}

	// 检查设备是否在线
	if !device.IsOnline() {
		return &gb28181.PlaybackResponse{
			Success: false,
			Message: "设备不在线",
		}, nil
	}

	// 验证时间范围
	if in.StartTime == "" || in.EndTime == "" {
		return &gb28181.PlaybackResponse{
			Success: false,
			Message: "开始时间和结束时间不能为空",
		}, nil
	}

	// 构建录像回放URL
	playbackUrl := l.buildPlaybackUrl(in.DeviceId, in.ChannelId, in.StartTime, in.EndTime)

	return &gb28181.PlaybackResponse{
		Success: true,
		Message: "录像回放启动成功",
		StreamUrl: playbackUrl,
	}, nil
}

// 构建录像回放URL
func (l *PlaybackLogic) buildPlaybackUrl(deviceId, channelId, startTime, endTime string) string {
	// 根据配置构建录像回放URL
	config := l.svcCtx.Config.GB28181Config
	return fmt.Sprintf("rtsp://%s:%d/%s/%s?start=%s&end=%s", config.SIPServerHost, 554, deviceId, channelId, startTime, endTime)
}
